import { Location } from '@angular/common';
import { Injectable } from '@angular/core';
import { _HttpClient, Menu, MenuService, SettingsService } from '@delon/theme';

@Injectable({
  providedIn: 'root'
})
export class MenusReloadService {
  constructor(
    private settingService: SettingsService,
    private http: _HttpClient,
    private menuService: MenuService,
    private location: Location
  ) {}

  reloadAntMenu() {
    // const user = this.settingService.getData('user');
    this.http.get(`api/user_menus`).subscribe(res => {
      let menuData = this.formatAntMenu(res.data);
      this.menuService.add(menuData);
      console.log(this.location.path());
      this.menuService.openedByUrl(this.location.path());
      this.menuService.resume();
    });
  }

  formatAntMenu(menuData: any): Menu[] {
    for (let i = 0; i < menuData.length; i++) {
      if (menuData[i].type == 0) {
        menuData[i].group = true;
      }
      if (menuData[i].children == null) {
        delete menuData[i].children;
        continue;
      }
      this.formatAntMenu(menuData[i].children);
    }
    return menuData;
  }
}
